import { useEffect } from 'react';
import AppRouter from './router';
import { useConfig } from '@stores/appStore';
import {
  useGlobalShortcuts,
  useNotifications,
  useAppConfig,
} from '@hooks/useTauri';
import {
  initializeI18n,
  useI18nStore,
  useTranslation,
  getBestLanguageChoice,
} from './i18n';
import './App.css';

function App() {
  const config = useConfig();
  const { registerShortcut } = useGlobalShortcuts();
  const { requestPermission } = useNotifications();
  const { loadConfig } = useAppConfig();
  const { changeLanguage } = useTranslation();

  useEffect(() => {
    // Initialize app on startup
    initializeApp();
  }, []);

  useEffect(() => {
    // Apply theme on config change
    applyTheme(config.theme);
  }, [config.theme]);

  useEffect(() => {
    // Register global shortcuts
    registerGlobalShortcuts();
  }, [config.shortcuts]);

  useEffect(() => {
    // Sync language between app config and i18n store
    if (config.language) {
      syncLanguageSettings(config.language);
    }
  }, [config.language]);

  const initializeApp = async () => {
    try {
      // Request notification permission
      await requestPermission();

      // Load saved configuration from backend
      await loadConfig();

      console.log('App initialized');
    } catch (error) {
      console.error('Failed to initialize app:', error);
    }
  };

  // Initialize i18n when config is loaded
  useEffect(() => {
    const initI18n = async () => {
      try {
        const { currentLanguage, resources } = useI18nStore.getState();

        // Determine the best language to use
        const targetLanguage = getBestLanguageChoice(config?.language);

        // Check if we need to initialize or switch language
        const needsInitialization = Object.keys(resources).length === 0;
        const needsLanguageSwitch = currentLanguage !== targetLanguage;

        if (needsInitialization || needsLanguageSwitch) {
          console.log(
            `Initializing i18n with language: ${targetLanguage} (from config: ${config?.language || 'none'})`
          );
          await initializeI18n(targetLanguage);

          // Sync the language setting back to the store if it was changed during initialization
          const { currentLanguage: finalLanguage } = useI18nStore.getState();
          if (finalLanguage !== targetLanguage) {
            console.log(
              `Language fallback occurred: ${targetLanguage} -> ${finalLanguage}`
            );

            // If we fell back to a different language and no config language was set,
            // we might want to save the detected language to config
            if (!config?.language && finalLanguage !== 'en') {
              console.log(
                `Detected system language: ${finalLanguage}, consider saving to config`
              );
            }
          }
        } else {
          console.log(
            `i18n already initialized with correct language: ${currentLanguage}`
          );
        }
      } catch (error) {
        console.error('Failed to initialize i18n:', error);
        // Try to initialize with default language as last resort
        try {
          await initializeI18n('en');
        } catch (fallbackError) {
          console.error(
            'Failed to initialize i18n with fallback language:',
            fallbackError
          );
        }
      }
    };

    // Initialize i18n when we have config or on first load
    if (config !== null) {
      // config can be an empty object, so check for null specifically
      initI18n();
    }
  }, [config]);

  const syncLanguageSettings = async (language: string) => {
    try {
      // Update i18n store to match app config
      const { currentLanguage } = useI18nStore.getState();
      if (currentLanguage !== language) {
        await changeLanguage(language as any);
      }
    } catch (error) {
      console.error('Failed to sync language settings:', error);
    }
  };

  const applyTheme = (theme: string) => {
    const root = document.documentElement;

    if (theme === 'dark') {
      root.classList.add('dark');
    } else if (theme === 'light') {
      root.classList.remove('dark');
    } else {
      // System theme
      const prefersDark = window.matchMedia(
        '(prefers-color-scheme: dark)'
      ).matches;
      if (prefersDark) {
        root.classList.add('dark');
      } else {
        root.classList.remove('dark');
      }
    }
  };

  const registerGlobalShortcuts = async () => {
    try {
      // Register toggle window shortcut
      if (config.shortcuts.toggleWindow) {
        await registerShortcut(config.shortcuts.toggleWindow, () => {
          // Toggle window visibility
          console.log('Toggle window shortcut pressed');
        });
      }

      // Register new item shortcut
      if (config.shortcuts.newItem) {
        await registerShortcut(config.shortcuts.newItem, () => {
          // Create new item
          console.log('New item shortcut pressed');
        });
      }

      // Register search shortcut
      if (config.shortcuts.search) {
        await registerShortcut(config.shortcuts.search, () => {
          // Open search
          console.log('Search shortcut pressed');
        });
      }
    } catch (error) {
      console.error('Failed to register shortcuts:', error);
    }
  };

  return (
    <div className="App">
      <AppRouter />
    </div>
  );
}

export default App;
